<template>
  <view class="pay">
    {{token}}
    <!-- 1 收货地址 -->
    <view class="address u-p-20">
      <view class="address-btn u-flex u-row-center">
        <!-- 有地址就隐藏获取地址按钮 显示地址-->
        <view v-if="address" class="address-detail">
        <!-- 显示地址 -->
        <view class="address-detail">{{detailAddress}}</view>
        <view class="address-user">
          <!-- 姓名 -->
          <text>{{address.userName}}</text>
          <!-- 电话号码 -->
          <text>{{address.telNumber}}</text>
        </view>
      </view>
      <!-- 否则就显示 获取收获地址按钮 -->
        <u-button
          v-else
          shape="circle"
          type="error"
          plain
          size="medium"
          :custom-style="{ backgroundColor: '#fff!important' }"
          @click="handleChooseAddress"
          >获取收货地址</u-button
        >
      </view>

      
    </view>

    <u-line color="#eee"></u-line>

    <!-- 2 已选商品 -->
    <view class="goods-list u-p-15">
      <view class="goods-list-title">已选商品</view>
      <view class="goods-list-content">
        <view class="cart-item" v-for="item in checkedCarts" :key="item.goods_id">
          <!-- 2 图片 -->
          <view class="goods-img">
            <u-image width="191rpx" height="191rpx" :src="item.goods_small_logo"></u-image>
          </view>
          <!-- 3 信息 -->
          <view class="goods-info">
            <!-- 名称 -->
            <view class="goods-name u-line-2">{{item.goods_name}}</view>
            <!-- 价格和数量 -->
            <view class="goods-price-num">
              <view class="goods-price">￥{{item.goods_price}}</view>
              <view class="goods-num-tool">
                <view class="goods-vnum">X{{item.num}}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 2 统计 -->
    <view class="statistics">
      <view class="all-price"> 合计: <text>￥{{checkedCartPrice}}</text> </view>
      <view class="all-count">
        <u-button type="error" shape="circle" @click="handlePay">去支付({{checkedCartNums}})</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions, mapState } from "vuex";
export default {
  data(){
    return{
      // 收货地址
      address: null,
    }
  },
  methods:{
    ...mapActions('user',['fetchToken']),
    // 点击 收获地址按钮 事件
   async handleChooseAddress(){
      const [err,result] = await uni.chooseAddress()
      console.log(result);
      this.address = result
    },
    // 点击 去支付 事件
   async handlePay(){
    // this.fetchToken()
    // return
    // 1、获取用户信息
      // getUserProfile 必须要通过点击按钮直接获取  其他方式获取不到（定时器、在点击事件处理后面）
      // const [err1, result1] = await uni.getUserProfile({
      //   desc: '用来给用户提供更好的体验',
      // });
      // // console.log(err1);
      // // console.log(result1);

      // // 2、调用 wx.login 来获取 code （临时登录凭据 5分钟有效）
      // const [err2,{code}] = await uni.login()
      // // console.log(err2);
      // // console.log(code);

      // // 调用后台接口  获取token
      // const result3 = await this.$u.post('/users/wxlogin',{
      //   ...result1,
      //   code,
      // })

      // 判断有没有token 如果没有则调用action来获取token  ---vuex
      if(!this.token){
        // 获取token
        await this.fetchToken();
      }

      // console.log(result3);  //登录成功  获取到token
      // const {token} = result3.message

      // 二、1. 调用创建订单接口
      //创建订单
      const orderParams = {
        // 		订单总价格 string类型
        order_price: this.checkedCartPrice,
        //    收货地址	 string类型	
        consignee_addr: this.detailAddress,
        // 		订单数组   Array类型
        goods: this.checkedCarts.map((v) => ({
          goods_id: v.goods_id,
          goods_number: v.num,
          goods_price: v.goods_price,
        })),
      };
      // 2 调用创建订单接口
      // post (请求路径url,请求参数,请求头/token)
      const result4 = await this.$u.post('/my/orders/create', orderParams);
      console.log(result4);

      // 订单编号
      const { order_number } = result4.message;

      // 3.获取支付参数
      // post (请求路径url,请求参数,请求头/token)
      const result5 = await this.$u.post('/my/orders/req_unifiedorder', {
        order_number,
      });

      // 支付参数
      const {pay} = result5.message;

      // 4.调用小程序内API 微信支付
      await uni.requestPayment(pay)

      // 5.查询订单的状态
      const result6 = await this.$u.post('/my/orders/chkOrder',{order_number},{
        Authorization: token,
      })
      console.log(result6);
      // 提示框
      uni.showToast({
        title:'result6.message',
      })
      
      // 弹窗显示一会之后，应该跳转到订单页面
      setTimeout(()=>{
        console.log('即将跳转到订单页面');
      },1500)
    }
  },
  // 计算属性
  computed:{
    // checkedCarts 选中的商品（购物车存在的商品）--数组
    // checkedCartNums 总数量
    // checkedCartPrice 总价格
    ...mapGetters('cart', ['checkedCarts','checkedCartNums','checkedCartPrice']),
    ...mapState('user',['token']),
    // 详细收获地址信息
    detailAddress(){
      if (!this.address) return ''
      const {provinceName, cityName, countyName, detailInfo} = this.address
      return provinceName + cityName + countyName + detailInfo
    }
  }
};
</script>

<style lang="scss">
.pay {
  padding-bottom: 111rpx;
}
.cart-item {
  display: flex;
  padding: 10rpx;
  border-bottom: 1rpx solid #ccc;

  .goods-img {
    flex: 2;

    display: flex;
    align-items: center;
    justify-content: center;
  }

  .goods-info {
    color: #666;
    flex: 3;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .goods-name {
    }

    .goods-price-num {
      display: flex;
      justify-content: space-between;
      .goods-price {
        color: #eb4450;
      }

      .goods-num-tool {
        width: 140rpx;
        height: 40rpx;

        display: flex;
        justify-content: flex-end;

        .goods-vnum {
        }
      }
    }
  }
}
.statistics {
  position: fixed;
  background-color: #fff;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 100;
  border-top: 1rpx solid #ccc;
  display: flex;
  align-items: center;
  padding: 15rpx;
  .all-price {
    flex: 1;
    color: #666;
    text {
    }
  }

  .all-count {
  }
}
</style>